package source
{
	import com.justinbuser.net.DynamicURLLoader;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayList;
	
	import spark.core.ContentCache;

	[Event(name="fullReportLoaded", type="flash.events.Event")]
	
	[Bindable] public class FullBattleReport extends EventDispatcher
	{
		public var id:Number;
		public var reportLabel:String;
		public var prizes:ArrayList = new ArrayList();
		public var teams:Array = new Array();
		public var players:Vector.<BattlePersona> = new Vector.<BattlePersona>();
		public var topBmD:BattlePersona;
		
		public const awardTypes:Object = {kills:{awardLabel:"Most Kills:",scoreLabel:"Kills:"},
			awardscore:{awardLabel:"Top Award Score:",scoreLabel:"Awards Score:"},
			vehiclecrew:{awardLabel:"Top Vehicle Operator:",scoreLabel:"Vehicle Score:"},
			jetcrew:{awardLabel:"Top Jet Pilot:",scoreLabel:"Jet Score:"},
			helicrew:{awardLabel:"Top Helicopter Pilot:",scoreLabel:"Helicopter Score:"},
			accuracy:{awardLabel:"Most Accurate:",scoreLabel:"Accuracy:"},
			recon:{awardLabel:"Top Recon:",scoreLabel:"Recon Score:"},
			support:{awardLabel:"Top Support:",scoreLabel:"Support Score:"},
			assault:{awardLabel:"Top Assault:",scoreLabel:"Assault Score:"},
			engineer:{awardLabel:"Top Engineer:",scoreLabel:"Engineer Score:"}};
		
		[Embed(source="default-avatar-190.png")] public static const defaultBitmapFull:Class;
		[Embed(source="default-avatar-100.png")] public static const defaultBitmapThumb:Class;
		
		public static const gravBase:String = "http://www.gravatar.com/avatar/";
		public static const defaultImage:String = "http://battlelog-cdn.battlefield.com/public/base/shared/default-avatar-190.png";
		public static const fullRedir:String = "?s=200&d="+defaultImage;
		public static const thumbRedir:String = "?s=100&d="+defaultImage;
		public static const squads:Object = {0:'None',1:'Alpha',2:'Bravo',3:'Charlie',4:'Delta',5:'Echo',6:'Foxtrot',7:'Golf',8:'Hotel'};
		public static var gravatarCache:ContentCache;
		public static var rankCache:ContentCache;
		
		public function FullBattleReport(report:Object=null,label:String=null)
		{
			if(!gravatarCache)
			{
				gravatarCache = new ContentCache();
				gravatarCache.enableCaching = true;
				gravatarCache.enableQueueing = true;
				/*gravatarCache.maxActiveRequests = 1;
				gravatarCache.maxCacheEntries = 30;*/
				gravatarCache.addCacheEntry(defaultImage,defaultBitmapFull);
			}
			if(!rankCache)
			{
				rankCache = new ContentCache();
				rankCache.enableCaching = true;
				rankCache.enableQueueing = true;
				/*rankCache.maxActiveRequests = 1;
				rankCache.maxCacheEntries = 30;*/
			}
			if(report)
			{
				try{
					id = report.id;
					reportLabel = label;
				}
				catch(e:Error){
					trace("FullBattleReport error:",e.getStackTrace(),"\n",JSON.stringify(report));
				}
				
				for each(var award:Object in report.prizes)
				{
					try{
						var prize:BattleAward = new BattleAward();
						prize.awardLabel=awardTypes[award.type].awardLabel;
						prize.scoreLabel=awardTypes[award.type].scoreLabel;
						prize.personaId = String(award.personaId);
						prize.userScore = award.score;
						if(award.type == "accuracy") prize.userScore += "%";
						prizes.addItem(prize);
						//prizes[prize.personaId] = prize;
					}
					catch(e:Error){
						trace("FullBattleReport error:",e.getStackTrace(),"\n",JSON.stringify(report));
					}
				}
				
				var teamFactionMapping:Object = report.teamFactionMapping;

				for(var team:String in report.players)
				{
					var members:Array = report.players[team];
					var teamPersonas:Vector.<BattlePersona> = new Vector.<BattlePersona>();
					//
					for(var i:int = 0; i < members.length; i++)
					{
						var persona:BattlePersona = new BattlePersona();
						persona.personaId = String(members[i].personaId);
						persona.userId = String(members[i].userId);
						persona.kills = members[i].kills;
						persona.deaths = members[i].deaths;
						persona.rank = members[i].rank;
						persona.killAssists = members[i].killAssists;
						persona.squad = squads[members[i].squadId];
						persona.team = teamFactionMapping[members[i].team];
						persona.combatScore = members[i].combatScore;
						if(members[i].user == null)
						{
							persona.gravatarURL = defaultBitmapFull;
							persona.gravatarThumbURL = defaultBitmapThumb;
						}
						else
						{
							persona.gravatarURL = gravBase+members[i].user.gravatarMd5+fullRedir;
							persona.gravatarThumbURL = gravBase+members[i].user.gravatarMd5+thumbRedir;
						}
						if(persona.userId != "None")
						{
							fetchUser(Object(persona).valueOf(),String(report.platform));
						}
						else if(members[i].persona)
						{
							persona.personaName = members[i].persona.personaName;
							if(members[i].persona.namespace != null)
							{
								persona.namespace = members[i].persona.namespace;
								persona.profileURL = "http://battlelog.battlefield.com/bf3/soldier/"+persona.personaName+"/stats/"+persona.personaId+"/"+persona.namespace+"/";
							}
							for(var ii:int = 0; ii < prizes.length; ii++)
							{
								if(String(prizes.getItemAt(ii).personaId) == persona.personaId)
								{
									BattleAward(prizes.getItemAt(ii)).battlePersona = persona;
									prizes.itemUpdated(prizes.getItemAt(ii),'battlePersona');
									trace('Prize:',BattleAward(prizes.getItemAt(ii)).awardLabel,'awared to:',BattleAward(prizes.getItemAt(ii)).battlePersona.personaName,' with personaId:',BattleAward(prizes.getItemAt(ii)).personaId);
								}
							}
							players.push(persona);
						}
						teamPersonas.push(Object(persona).valueOf());
					}
					teams.push({label:teamFactionMapping[team],winners:Boolean(team == report.winner),personas:teamPersonas.concat()});
					trace('added:',teamFactionMapping[team]);
				}
			}
			
		}
		
		private function fetchUser(persona:BattlePersona,platform:String):void{
			//trace('loading personaId:',persona.personaId,'userId:',persona.userId,'from:',"http://battlelog.battlefield.com/all/user/overviewBoxStats/"+persona.userId+"/");
			var loader:DynamicURLLoader = new DynamicURLLoader(parseUser);
			loader.open("http://battlelog.battlefield.com/all/user/overviewBoxStats/"+persona.userId+"/",null,1,"GET");
			
			function parseUser(e:Event):void{
				var result:Object = JSON.parse(e.target.data);
				var soldiersBox:Array = result.data.soldiersBox;
				if(soldiersBox.length > 0)
				{
					for(var i:int = 0; i < soldiersBox.length; i++)
					{
						if(String(soldiersBox[i].persona.personaId) == persona.personaId)
						{
							persona.personaName = soldiersBox[i].persona.personaName;
							persona.clanTag = soldiersBox[i].persona.clanTag;
							if(soldiersBox[i].persona.namespace != null)
							{
								persona.namespace = soldiersBox[i].persona.namespace;
								persona.profileURL = "http://battlelog.battlefield.com/bf3/soldier/"+persona.personaName+"/stats/"+persona.personaId+"/"+persona.namespace+"/";
							}
							for(var ii:int = 0; ii < prizes.length; ii++)
							{
								if(String(prizes.getItemAt(ii).personaId) == persona.personaId)
								{
									var prize:BattleAward = BattleAward(prizes.getItemAt(ii));
									prize.battlePersona = persona;
									prizes.itemUpdated(prize,'battlePersona');
									trace('Prize:',prize.awardLabel,'awared to:',prize.battlePersona.personaName,' with personaId:',prize.personaId);
								}
							}
							if(persona.clanTag == "bMd"){
								var adjustedScore:Number = ( ( persona.kills + ( persona.killAssists / 2 ) ) / persona.deaths) * persona.combatScore;
								persona.sanitizedScore = adjustedScore;
								if(!topBmD)
								{
									topBmD = Object(persona).valueOf();
									var bMdAward:BattleAward = new BattleAward();
									bMdAward.awardLabel = "Top Boogieman: ";
									bMdAward.scoreLabel = "Sanitized Score: ";
									bMdAward.userScore = String(adjustedScore.valueOf());
									bMdAward.battlePersona = topBmD;
									prizes.addItemAt(bMdAward,0);
								}
								else if(adjustedScore > Number(topBmD.sanitizedScore)) 
								{
									topBmD = Object(persona).valueOf();
									prizes.getItemAt(0).userScore = adjustedScore.valueOf();
									prizes.getItemAt(0).battlePersona = topBmD;
								}
							}
							players.push(persona);
						}
					}
				}
			}
			
		}
		
		/*private function fetchPersona(persona:BattlePersona,platform:String):void{
			var loader:DynamicURLLoader;
			trace('fetching userId for personaId:',persona.personaId,'from:',"http://battlelog.battlefield.com/bf3/overviewPopulateStats/"+persona.personaId+"/0/"+platform+"/");
			loader = new DynamicURLLoader(parsePersona);
			loader.open("http://battlelog.battlefield.com/bf3/overviewPopulateStats/"+persona.personaId+"/0/"+platform+"/",null,1,"GET");
			
			function parsePersona(e:Event):void{
				var result:Object = JSON.parse(e.target.data);
				persona.userId = String(result.data.user.userId);
				fetchUser(Object(persona).valueOf(),platform);
			}
		}*/
		
	}
}